package com.eco.fanliapp.service.impl;

import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 淘礼金免单商品 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-11-27
 */
@Service
public class SyTljGoodsfreeServiceImpl extends ServiceImpl<SyTljGoodsfreeMapper, SyTljGoodsfree> implements ISyTljGoodsfreeService {
    @Autowired
    private SyTljGoodsfreeMapper syTljGoodsfreeMapper;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private FindItemIdUtils taoBaoUtils;
    @Autowired
    private GoodsFreeMapper goodsFreeMapper;
    @Autowired
    private SyChannelGoodsMapper syChannelGoodsMapper;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private ITaoBaoService taoBaoService;
    @Autowired
    private IAdministratorService administratorService;
    @Autowired
    private SysLogCommon sysLogCommon;
    @Override
    public ServerResponse selectTljGoodsfree(Integer pageNum, Integer pageSize, String date) {
        PageHelper.startPage(pageNum, pageSize);
        List<SyTljGoodsfree> syTljGoodsfrees = syTljGoodsfreeMapper.selectTljGoodsfreeList(date);
        return ServerResponse.createBySuccess(new PageInfo(syTljGoodsfrees));
    }




    @Override
    public ServerResponse insertTljGoodsfree(SyTljGoodsfree syTljGoodsfree, UserVO authentication) {
        if (syTljGoodsfree.getItemId() == null) {
            return ServerResponse.createByErrorMessage("商品Id不可为空");
        }
        if (syTljGoodsfree.getFailureTime() == null) {
            return ServerResponse.createByErrorMessage("商品过期时间不可为空");
        }

        //判断是否在免单,高佣商品中存在
        SyChannelGoods syChannelGoods = syChannelGoodsMapper.selectChannelGoodsById(syTljGoodsfree.getItemId());
        HashMap<String, Object> goodsFreeMap = new HashMap<>();
        goodsFreeMap.put("goodsId", syTljGoodsfree.getItemId().toString());
        goodsFreeMap.put("goodsStatus", 2);
        List<GoodsFree> goodsFree = goodsFreeMapper.selectByGoodsIds(goodsFreeMap);
        if (syChannelGoods != null || goodsFree.size() > 0) {
            return ServerResponse.createByErrorMessage("商品已经在免单或高佣商品中存在");
        }

        List<SyTljGoodsfree> syTljGoodsfrees = syTljGoodsfreeMapper.selectTljGoodsfreeList(DateUtils.date2Strday(new Date()));
        //判断商品今日是否已添加
        if (syTljGoodsfrees != null) {
            for (SyTljGoodsfree syTljGoodsfree1 : syTljGoodsfrees) {
                if (syTljGoodsfree1.getItemId().equals(syTljGoodsfree.getItemId())) {
                    return ServerResponse.createByErrorMessage("商品已存在");
                }
            }
        }
        SysLog sysLog = new SysLog();
        Administrator administrator = administratorService.getById(authentication.getUserId());
        sysLog.setUserId(authentication.getUserId());
        sysLog.setMethodExplain(administrator.getAdminitratorName()+"新增了tlj商品"+syTljGoodsfree.getItemId());
        String exchangeCode = getNum(8);
        AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(syTljGoodsfree.getItemId().toString());
        if (appGoods != null) {
            syTljGoodsfree.setItemName(appGoods.getItemshorttitle());
            syTljGoodsfree.setItemPic(appGoods.getItempic());
            syTljGoodsfree.setOriginalPrice(new BigDecimal(appGoods.getItemprice()));
            syTljGoodsfree.setDiscountPrice(new BigDecimal(appGoods.getItemendprice()));
            syTljGoodsfree.setTkMoney(new BigDecimal(appGoods.getTkmoney()));
            syTljGoodsfree.setExchangeCode(exchangeCode);
            int i = syTljGoodsfreeMapper.insertTljGoodsfree(syTljGoodsfree);
            if (i > 0) {
                appGoods.setItemTop(7);
                appGoods.setRecommend(1);
                appGoodsMapper.updateAppGoods(appGoods);
//                List<AppGoods> appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
//                taoBaoService.getRedisRecommendGoodsList(appGoodsList);
                String redskey= "sy_tlj_zero_buy_goodsFree";
                redisTemplateService.del(redskey);
                sysLog.setResponseParams("新增成功");
                sysLogCommon.save(sysLog);
                return ServerResponse.createBySuccess("新增成功");
            } else {
                sysLog.setResponseParams("新增失败");
                sysLogCommon.save(sysLog);
                return ServerResponse.createByErrorMessage("新增失败");
            }
        } else {
            //如果不存在查好单库
            HaoDanKuItemInfo info = taoBaoUtils.getHaoDanKuItemId(syTljGoodsfree.getItemId().toString());
            if (info != null && info.getCode() == 1 && info.getData() != null) {
                syTljGoodsfree.setItemName(info.getData().getItemtitle());
                syTljGoodsfree.setItemPic(info.getData().getItempic());
                syTljGoodsfree.setOriginalPrice(new BigDecimal(info.getData().getItemprice()));
                syTljGoodsfree.setDiscountPrice(new BigDecimal(info.getData().getItemendprice()));
                syTljGoodsfree.setTkMoney(new BigDecimal(info.getData().getTkmoney()));
                syTljGoodsfree.setExchangeCode(exchangeCode);
                int i = syTljGoodsfreeMapper.insertTljGoodsfree(syTljGoodsfree);
                if (i > 0) {
                    AppGoods goods = HDKUtils.getAppGoodsFromHDK(info.getData());
                    goods.setItemTop(7);
                    goods.setRecommend(1);
                    int i2 = appGoodsMapper.insertAppGoods(goods);
                    if (i2 > 0) {
//                        List<AppGoods> appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
//                        taoBaoService.getRedisRecommendGoodsList(appGoodsList);
                        String redskey= "sy_tlj_zero_buy_goodsFree";
                        redisTemplateService.del(redskey);
                        sysLog.setResponseParams("添加成功");
                        sysLogCommon.save(sysLog);
                        return ServerResponse.createBySuccessMessage("添加成功");
                    } else {
                        sysLog.setResponseParams("新增失败");
                        sysLogCommon.save(sysLog);
                        return ServerResponse.createByErrorMessage("添加失败");
                    }
                } else {
                    sysLog.setResponseParams("新增失败");
                    sysLogCommon.save(sysLog);
                    return ServerResponse.createByErrorMessage("添加失败");
                }
            } else {
                //查询淘宝详情
                List<TbkItemInfoGetInfo.NTbkItem> items = taoBaoUtils.getTaoBaoItemId(syTljGoodsfree.getItemId().toString());
                if (items != null && items.size() > 0) {
                    for (TbkItemInfoGetInfo.NTbkItem nTbkItem : items) {
                        TbkPrivilegeGetInfo.TbkPrivilege privilege = taoBaoUtils.getPrivilegeItemId(syTljGoodsfree.getItemId());
                        syTljGoodsfree.setItemName(nTbkItem.getTitle());
                        syTljGoodsfree.setItemPic(nTbkItem.getPictUrl());
                        syTljGoodsfree.setOriginalPrice(new BigDecimal(nTbkItem.getZkFinalPrice()));
                        BigDecimal itemendprice = BigDecimalUtils.Format(
                                new BigDecimal(nTbkItem.getZkFinalPrice() == null ? "0" : nTbkItem.getZkFinalPrice())
                                        .subtract(new BigDecimal(privilege.getCouponInfo()))
                        );
                        syTljGoodsfree.setDiscountPrice(itemendprice);
                        syTljGoodsfree.setTkMoney(new BigDecimal(info.getData().getTkmoney()));
                        syTljGoodsfree.setExchangeCode(exchangeCode);
                        int i = syTljGoodsfreeMapper.insertTljGoodsfree(syTljGoodsfree);
                        if (i > 0) {
                            AppGoods goods2 = HDKUtils.getAppGoodsFromTB(nTbkItem);
                            goods2.setItemTop(7);
                            goods2.setRecommend(1);
                            goods2.setCouponmoney(Double.valueOf(privilege.getCouponInfo()));
                            goods2.setCouponstarttime(privilege.getCouponStartTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponStartTime()).toString());
                            goods2.setCouponendtime(privilege.getCouponEndTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
                            goods2.setEndTime(privilege.getCouponEndTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
                            BigDecimal itemendprice1 = BigDecimalUtils.Format(
                                    new BigDecimal(nTbkItem.getZkFinalPrice() == null ? "0" : nTbkItem.getZkFinalPrice())
                                            .subtract(new BigDecimal(privilege.getCouponInfo()))
                            );
                            goods2.setItemendprice(itemendprice1.doubleValue());
                            goods2.setTkrates(privilege.getMaxCommissionRate());
                            goods2.setItemprice(nTbkItem.getZkFinalPrice());
                            goods2.setCreateTime(DateUtils.getNowTimestamp());
                            goods2.setUpdateTime(DateUtils.getNowTimestamp());
                            int i2 = appGoodsMapper.insertAppGoods(goods2);
                            if (i2 > 0) {
//                                List<AppGoods> appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
//                                taoBaoService.getRedisRecommendGoodsList(appGoodsList);
                                String redskey= "sy_tlj_zero_buy_goodsFree";
                                redisTemplateService.del(redskey);
                                sysLog.setResponseParams("商品添加成功");
                                sysLogCommon.save(sysLog);
                                return ServerResponse.createBySuccessMessage("商品添加成功");
                            } else {
                                sysLog.setResponseParams("新增失败");
                                sysLogCommon.save(sysLog);
                                return ServerResponse.createByErrorMessage("商品添加失败");
                            }
                        } else {
                            sysLog.setResponseParams("新增失败");
                            sysLogCommon.save(sysLog);
                            return ServerResponse.createByErrorMessage("商品添加失败");
                        }
                    }
                }
                return ServerResponse.createByErrorMessage("商品不存在");
            }
        }
    }

    @Override
    public ServerResponse deleteTljGoodsfree(Integer tableId) {
        int i = syTljGoodsfreeMapper.deleteTljGoodsfree(tableId);
        SyTljGoodsfree goodsfree = syTljGoodsfreeMapper.selectTljGoodsfreeByTableId(tableId);
        if (goodsfree != null) {
            AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(goodsfree.getItemId().toString());
            if (appGoods != null) {
                appGoods.setRecommend(0);
                appGoods.setItemTop(1);
                appGoodsMapper.updateAppGoods(appGoods);
//                List<AppGoods> appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
//                taoBaoService.getRedisRecommendGoodsList(appGoodsList);
                String redskey= "sy_tlj_zero_buy_goodsFree";
                redisTemplateService.del(redskey);
            }
        }
        if (i > 0) {
            return ServerResponse.createBySuccess("删除成功",tableId);
        }
        return ServerResponse.createBySuccess("删除失败",tableId);
    }

    @Override
    public ServerResponse ishasItemId(Long itemId) {
        if (itemId == null) {
            return ServerResponse.createByErrorMessage("商品Id不可为空");
        }
        List<SyTljGoodsfree> syTljGoodsfrees = syTljGoodsfreeMapper.selectTljGoodsfreeList(DateUtils.date2Strday(new Date()));
        //判断商品今日是否已添加
        if (syTljGoodsfrees != null) {
            for (SyTljGoodsfree syTljGoodsfree1 : syTljGoodsfrees) {
                if (syTljGoodsfree1.getItemId().equals(itemId)) {
                    return ServerResponse.createByErrorMessage("今日商品已存在");
                }
            }
        }
        return ServerResponse.createBySuccess();
    }

    /**
     * H50元购淘礼金商品
     * @return
     * @param userId
     * @param version
     */
    @Override
    public ServerResponse zeroBuyDetails(Long userId, String version) {
        String redskey= "sy_tlj_zero_buy_goodsFree";
        List<AppGoods> list = null;
        List<AppGoodsVo> listVo;
        if(redisTemplateService.hasKey(redskey)){
            list = redisTemplateService.getTByListKey(redskey,AppGoods.class);
        }
        if(list == null || list.size() == 0){
            list = appGoodsMapper.selectTljGoods();
            redisTemplateService.set(redskey,list,60*5);
        }

        if(list == null || list.size() == 0 ){
            return ServerResponse.createBySuccessCodeMessage(201,"活动正在筹备中，马上就来~");
        }else {
            listVo = taoBaoService.getAppGoodsVo(userId,list,null,null,version);
            for (AppGoodsVo appGoodsVo:listVo
                 ) {
                appGoodsVo.getLabelTypeTitle().add("0元购—社群专享");
            }
            return ServerResponse.createBySuccess(listVo);
        }
    }

    /**
     * 限时漏洞
     * @param userId
     * @param version
     * @return
     */
    @Override
    public ServerResponse loopholeDetails(Long userId, String version) {
        String redskey= "sy_tlj_loophole_goods";
        List<AppGoods> list = null;
        List<AppGoodsVo> listVo;
        if(redisTemplateService.hasKey(redskey)){
            list = redisTemplateService.getTByListKey(redskey,AppGoods.class);
        }
        if(list == null || list.size() == 0){
            list = appGoodsMapper.selectChannelGoods();
            redisTemplateService.set(redskey,list,60*5);
        }

        if(list == null || list.size() == 0 ){
            return ServerResponse.createBySuccessCodeMessage(201,"活动正在筹备中，马上就来~");
        }else {
            listVo = taoBaoService.getAppGoodsVo(userId,list,null,null,version);
            for (AppGoodsVo appGoodsVo:listVo
            ) {
                //appGoodsVo.setItemShortTitle(appGoodsVo.getItemShortTitle() + "【限补贴1单】");
                appGoodsVo.getLabelTypeTitle().add("限时漏洞福利");
            }
            return ServerResponse.createBySuccess(listVo);
        }
    }

    public  String getNum(int digit) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < digit; i++) {
            if (i == 0 && digit > 1)
                str.append(new Random().nextInt(9) + 1);
            else
                str.append(new Random().nextInt(10));
        }
        return str.toString();
    }


}
